import {createRouter,createWebHistory,createWebHashHistory} from "vue-router";
import RouteConfig from "./config.js";
import {useRouterStore} from "../store/useRouterStore.js";
import {useUserStore} from "../store/useUserStore.js"
import MainBox from "../views/MainBox.vue";
import Login from "../views/Login.vue";

const routes =[
    {
        path: "/login",
        name:"Login",
        component:Login,
    },
    {
        path: "/mainbox",
        name:"Mainbox",
        component:MainBox,
    },
]

const router = createRouter({
    history:createWebHistory(),
    // history:createWebHashHistory(),
    routes,
})

//路由拦截
router.beforeEach( (to,from,next)=>{
    const {isGetterRouter}= useRouterStore()
    const {user}=useUserStore()
    if(to.name==="Login"){
       next()
    }
    else{
        if(!user.role){
            next({
                path: "/login"
            })
        }
        else {
                if(!isGetterRouter){
                    router.removeRoute("Mainbox")
                    ConfigRouter()
                    // console.log(!user.role+"已登录isGetterRouter:"+isGetterRouter+to.name)
                    next({
                        path:to.fullPath
                    })
                }else {
                    next()
                }
            }
        }


})

//动态添加路由
const ConfigRouter =()=>{
    // 创建mainbox
    router.addRoute({
        path:"/mainbox",
        name:"Mainbox",
        component:MainBox,
    })
    //添加路由
    let {changeRouter}=useRouterStore()
    RouteConfig.forEach(item=>{
        cheakPermissions(item.path)&&router.addRoute("Mainbox", item)
    })
    router.addRoute("Mainbox",{       //重定向
        path: "/",
        redirect:"/index",
    })
    router.addRoute("Mainbox",{       //404
        path: "/:lk(.*)*",
        component:()=>import("../views/notfound/notFound.vue"),
    })
    console.log(router.getRoutes())
    changeRouter(true)
}

const cheakPermissions=(path) => {
    const {user}=useUserStore()
    return user.role.rights.includes(path)
}

export default router